const express = require('express')
const monent = require('moment')
const AccountModel = require('../../models/AccountModel')
const checkLofinMiddleware = require('../../middlewares/checkLofinMiddleware')
const router = express.Router()

router.get('/', (req, res) => {
  res.redirect('/account')
})

router.get('/account', checkLofinMiddleware, function (req, res, next) {
  AccountModel.find()
    .sort({ time: -1 })
    .then((data) => {
      // console.log(data)
      res.render('list', { accounts: data, monent })
    })
    .catch((err) => {
      res.status(500).send('读取失败....')
    })
})

router.get('/account/create', checkLofinMiddleware, function (req, res, next) {
  res.render('create')
})

router.post('/account', checkLofinMiddleware, function (req, res, next) {
  AccountModel.create({
    ...req.body,
    time: monent(req.body.time).toDate()
  })
    .then((data) => {
      res.render('success', { msg: '添加成功哦~~~', url: '/account' })
    })
    .catch((err) => {
      res.status(500).send('插入失败...')
    })
})

router.get('/account/:id', checkLofinMiddleware, function (req, res, next) {
  let _id = req.params.id
  AccountModel.deleteOne({ _id })
    .then((data) => {
      res.render('success', { msg: '删除成功哦~~~', url: '/account' })
    })
    .catch((err) => {
      res.status(500).send('删除失败....')
    })
})

module.exports = router
